package com.veo.service.Impl;

import com.veo.dao.TagRespository;
import com.veo.entity.Tag;
import com.veo.exception.NotFoundException;
import com.veo.service.TagService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class TagServiceImpl implements TagService {

    @Autowired
    private TagRespository tagRespository;

    @Override
    public Tag saveTag(Tag tag) {
        return tagRespository.save(tag);
    }

    @Override
    public Tag getTag(Long id) {
        return tagRespository.findById(id).get();
    }

    @Override
    public Tag getTagByName(String name) {
        return tagRespository.findByName(name);
    }

    @Override
    public Page<Tag> listTag(Pageable pageable) {
        return tagRespository.findAll(pageable);
    }

    @Override
    public List<Tag> listTag() {
        return tagRespository.findAll();
    }

    @Override
    public List<Tag> listTagTop(Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC,"blogs.size");
        Pageable pageable = PageRequest.of(0,size,sort);
        return tagRespository.findTop(pageable);
    }

    @Override
    public List<Tag> listTag(String ids) {
        return tagRespository.findAllById(convertToList(ids));
    }

    //字符串转集合
    public List<Long> convertToList(String ids){
        List<Long> list = new ArrayList<>();
        if (!"".equals(ids) && ids != null){
            String[] idArray = ids.split(",");
            for (int i = 0; i < idArray.length; i++) {
                //如果传入的标签有字符串则进行一个标签的新增,新增后将新增的id 加入到list集合中
                try {
                    list.add(new Long(idArray[i]));
                }catch (NumberFormatException e){
                    Tag tag = new Tag();
                    tag.setName(idArray[i]);
                    Tag save = tagRespository.save(tag);
                    list.add(save.getId());
                    continue;
                }
            }
        }
        return list;
    }

    @Override
    public Tag updateTag(Long id, Tag tag) {
        Tag t = tagRespository.findById(id).get();
        if (t == null){
            throw new NotFoundException("不存在该类型的id---updateTag--id");
        }
        BeanUtils.copyProperties(tag,t);
        return tagRespository.save(t);
    }

    @Override
    public void deleteTag(Long id) {
        tagRespository.deleteById(id);
    }
}
